<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="datePicker">
          <el-form-item label="时间区间" size="small">
            <el-date-picker type="date" placeholder="选择开始日期" value-format="timestamp" v-model="searchForm.startTime"
            ></el-date-picker>
            <span>-</span>
            <el-date-picker type="date" placeholder="选择结束日期" value-format="timestamp" v-model="searchForm.endTime"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <!--        <el-col class="other"-->
        <!--                v-if="roleType === 0 || roleType === 1 || roleType === 3 || roleType === 5 || roleType === 7">-->
        <!--          <el-form-item label="所属团队" size="small" class="item-inline">-->
        <!--            <el-autocomplete-->
        <!--              v-model="searchForm.teamName"-->
        <!--              :fetch-suggestions="querySearchTeam"-->
        <!--              @select="handleSelectTeam"-->
        <!--              placeholder="请输入内容"-->
        <!--            >-->
        <!--            </el-autocomplete>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col class="professions">
          <el-form-item label="所属专业" size="small">
            <el-select v-model="searchForm.leadingDiscipline" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in parentProfessionList"
                :key="item.professionId"
                :label="item.professionName"
                :value="item.professionId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="singleDatePicker">
          <el-form-item size="small">
            <el-button type="warning" @click="dateChange(1)">月份</el-button>
            <el-button type="warning" @click="dateChange(2)">年份</el-button>
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <a target="_blank"
         :href="`${global.exportUrl}/statistical/export?${encodeURI(exportUrl)}`">
        <el-button type="warning" size="small" icon="el-icon-upload2">
          导出
        </el-button>
      </a>
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      @viewDetails="viewDetails"
      :show-summary="roleType !== 2?true:false"
      :teambalance="teambalanceList"
    >
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog title="详情" :visible.sync="outerVisible" width="1100px">
      <component :view-detail-list="viewDetailList" :is="prop" keep-alive></component>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getParentProfessionList
  } from '@/api/contractproject1'
  import {
    getList,
    selectTeam,
    getSum
  } from '@/api/teambalance1'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import administrativeTotal from './component/administrativeTotal'
  import personnelTotal from './component/personnelTotal'
  import invoiceTotal from './component/invoiceTotal'
  import marginTotal from './component/marginTotal'
  import costProjectTotal from './component/costProjectTotal'
  import otherTotal from './component/otherTotal'
  import managementFeeTotal from './component/managementFeeTotal'
  import notArrived from './component/notArrived'
  import accountTotal from './component/accountTotal'
  import contactsAmount from './component/contactsAmount'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate, timestamp } from '@/utils/index'

  const other = {
    props: ['colConfig'],
    methods: {
      viewDetails(scope, colConfig) {
        const viewDetailList = {}
        viewDetailList.prop = colConfig.prop
        viewDetailList.teamId = scope.row.teamId
        this.$emit('viewDetails', viewDetailList)
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] }}
        <el-button
            @click.native.prevent="viewDetails(scope,colConfig)"
            type="text"
            size="small">
            详情
         </el-button>
      </span>
  </el-table-column>
  `
  }

  const previousBalance = function(row, column) {
    const previousBalance = row.accountTotal + row.contactsAmount - row.taxesTotal - row.costProjectTotal - row.managementFeeTotal - row.otherCostTotal - row.marginTotal - row.otherTotal - row.administrativeTotal - row.personnelTotal
    return Math.round(previousBalance * 1000000) / 1000000 || 0
  }

  export default {
    components: {
      myTable,
      AreaSelect,
      administrativeTotal,
      personnelTotal,
      invoiceTotal,
      marginTotal,
      costProjectTotal,
      otherTotal,
      managementFeeTotal,
      notArrived,
      accountTotal,
      contactsAmount
    },
    data() {
      return {
        colConfigs: [
          { prop: 'teamName', label: '团队名称', width: '120', fixed: true },
          { prop: 'previousBalanceTotal', label: '上期余额(万元)', width: '150' },
          { prop: 'previousBalance', label: '本期利润(万元)', width: '150', formatter: previousBalance },
          { prop: 'nowBalance', label: '本期余额(万元)', width: '150' },
          { prop: 'teamBalanceTotal', label: '当前余额(万元)', width: '150' },
          { prop: 'accountTotal', label: '所有到账(万元)', width: '150', component: other },
          { prop: 'projectTotal', label: '到账总额(万元)', width: '150' },
          { prop: 'contractAmount', label: '合同总额(万元)', width: '150' },
          { prop: 'notArrived', label: '未到账(万元)', width: '150', component: other },
          { prop: 'invoiceTotal', label: '开票总额(万元)', width: '150', component: other },
          { prop: 'taxesTotal', label: '开票税金(万元)', width: '150' },
          { prop: 'costProjectTotal', label: '成本支出(万元)', width: '150', component: other },
          { prop: 'returnTaxesTotal', label: '返税金额总额(万元)', width: '150' },
          { prop: 'managementFeeTotal', label: '管理费(万元)', width: '150', component: other },
          { prop: 'otherCostTotal', label: '其他支出(万元)', width: '150' },
          { prop: 'contactsAmount', label: '往来账(万元)', width: '150', component: other },
          { prop: 'marginProcedureTotal', label: '保证金手续费(万元)', width: '150' },
          { prop: 'marginTotal', label: '保证金支出(万元)', width: '150', component: other },
          { prop: 'otherTotal', label: '其他管理费(万元)', width: '150', component: other },
          { prop: 'administrativeTotal', label: '行政费用(万元)', width: '150', component: other },
          { prop: 'personnelTotal', label: '人员费用(万元)', width: '150', component: other }
        ],
        searchForm: {},
        searchFormList: {},
        parentProfessionList: [],
        listLoading: true,
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        outerTitle: '',
        viewDetailList: {},
        prop: '',
        pca: pca,
        rules: {},
        visible: false,
        exportUrl: '', // 导出参数
        teambalanceList: [] // 用来替换合计的数组
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
      this.getParentProfessionList()
    },
    computed: {
      global() {
        return global
      },
      teamId() {
        return this.$store.state.user.teamId
      },
      roleType() {
        return this.$store.state.user.roleType
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.teamId = this.teamId
        this.listLoading = true
        if (this.roleType !== 2) {
          getSum(this.searchFormList).then(response => {
            const data = response.responseBody
            const teambalanceList = ['合计', '']
            data.previousBalanceTotalSum = '' // 清空上期余额
            for (const i in data) {
              teambalanceList.push(data[i])
            }
            this.teambalanceList = [...teambalanceList]
            this.teambalanceList.splice(4, 0, '') // 插入本期余额
          })
        }
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          if (this.searchFormList.startTime && this.searchFormList.endTime) {
            this.tableData.forEach(value => {
              const nowBalance = value.accountTotal + value.contactsAmount - value.taxesTotal - value.costProjectTotal - value.managementFeeTotal - value.otherCostTotal - value.marginTotal - value.otherTotal - value.administrativeTotal - value.personnelTotal
              value.nowBalance = Math.round((nowBalance + value.previousBalanceTotal) * 1000000) / 1000000 || 0
            })
          } else {
            this.tableData.forEach(value => {
              value.nowBalance = 0
            })
          }
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      getParentProfessionList() {
        getParentProfessionList().then(response => {
          this.parentProfessionList = response.responseBody
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.searchForm.teamId
        const params = {
          teamName: queryString
        }
        selectTeam(params).then(response => {
          for (const i of response.responseBody) {
            i.value = i.teamName
          }
          const nameList = response.responseBody
          callback(nameList)
        })
      },
      handleSelectTeam(item) {
        this.$set(this.searchForm, 'teamId', item.teamId)
        this.$set(this.searchForm, 'teamName', item.teamName)
      },
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      },
      viewDetails(viewDetailList) {
        this.outerVisible = true
        this.prop = viewDetailList.prop
        this.viewDetailList = {
          teamId: viewDetailList.teamId,
          startTimeStr: this.searchForm.startTime ? this.formatDate(this.searchForm.startTime) : '',
          endTimeStr: this.searchForm.endTime ? this.formatDate(this.searchForm.endTime) : ''
        }
      },
      currentMonth(time) {
        var date = time ? new Date(time) : new Date()
        var year = date.getFullYear() + ''
        var month = (date.getMonth() + 1) + ''
        // 本月第一天日期
        var begin = year + '-' + month + '-01 00:00:00'
        // 本月最后一天日期
        var lastDateOfCurrentMonth = new Date(year, month, 0)
        var end = year + '-' + month + '-' + lastDateOfCurrentMonth.getDate() + ' 00:00:00'
        this.$set(this.searchForm, 'startTime', timestamp(begin))
        this.$set(this.searchForm, 'endTime', timestamp(end))
      },
      currentYear(time) {
        var date = time ? new Date(time) : new Date()
        var year = date.getFullYear() + ''
        console.log(year)
        // 本年第一天日期
        var begin = year + '-01' + '-01 00:00:00'
        // 本年最后一天日期
        var end = year + '-12' + '-31 00:00:00'
        this.$set(this.searchForm, 'startTime', timestamp(begin))
        this.$set(this.searchForm, 'endTime', timestamp(end))
      },
      dateChange(type) {
        if (type === 1) {
          this.currentMonth(this.searchForm.startTime)
        } else {
          this.currentYear(this.searchForm.startTime)
        }
      }
    },
    watch: {
      'searchForm': {
        handler(newValue, oldValue) {
          let exportUrl = ''
          const searchForm = Object.assign({}, this.searchForm, { teamId: this.teamId })
          searchForm.startTimeStr = searchForm.startTime ? this.formatDate(searchForm.startTime) : ''
          searchForm.endTimeStr = searchForm.endTime ? this.formatDate(searchForm.endTime) : ''
          if (!searchForm.startTime) {
            delete searchForm.startTime
          }
          if (!searchForm.endTime) {
            delete searchForm.endTime
          }
          Object.keys(searchForm).map((key) => {
            exportUrl += key + '=' + searchForm[key] + '&'
          })
          this.exportUrl = exportUrl
        },
        immediate: true,
        deep: true // 深度监听
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }

    .table-btn {
      margin-bottom: 10px;

      & > button {
        margin: 0 20px;
      }

      .el-dialog {
        textarea {
          margin-top: 10px;
        }

        .el-checkbox {
          margin-right: 20px;
        }

        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
